<?php

namespace app\common\model\xiluhouse;

use think\Exception;
use think\exception\ErrorException;
use think\Model;

/**
 * 第三方表
 */
class UserThird extends Model
{
    // 表名
    protected $name = 'xiluhouse_user_third';
    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    // 追加属性
    protected $append = [
    ];
    public function jscode2session($code)
    {
        $wxmini = new \app\common\library\xiluhouse\Wxmini();
        $return = $wxmini->jscode2session($code);
        return [
            'status' => true,
            'data' => [
                'unionid' => isset($return['unionid']) ? $return['unionid'] : '',
                'openid' => isset($return['openid']) ? $return['openid'] : '',
                'session_key' => isset($return['session_key']) ? $return['session_key'] : '',
            ],
        ];
    }
    public function decryptUserInfo($post)
    {
        $wxmini = new \app\common\library\xiluhouse\Wxmini();
        $return = $wxmini->decryptData($post['session_key'], $post['iv'], $post['encryptedData']);
        return [
            'status' => true,
            'data' => [
                'nickname' => isset($return['nickName']) ? $return['nickName'] : '',
                'avatar' => isset($return['avatarUrl']) ? $return['avatarUrl'] : '',
                'gender' => isset($return['gender']) ? $return['gender'] : 0,
            ],
        ];
    }
    public function decryptPhoneNumber($post)
    {
        $wxmini = new \app\common\library\xiluhouse\Wxmini();
        //新版本授权
        try {
            if(!empty($post['code'])){
                $return = $wxmini->getPhoneNumber($post['code']);
            }else if($post['iv'] && $post['encryptedData']){
                $return = $wxmini->decryptData($post['session_key'], $post['iv'], $post['encryptedData']);
            }else{
                throw new Exception("参数错误");
            }
        }catch (Exception | ErrorException $e){
            return [
                'status' => false,
                'info'   => $e->getMessage(),
                'data' => [],
            ];
        }
        return [
            'status' => true,
            'data' => [
                'mobile' => isset($return['phoneNumber']) ? $return['phoneNumber'] : '',
            ],
        ];
    }
}
